package util;

import javax.xml.bind.JAXBContext;
import javax.xml.transform.Result;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import org.springframework.xml.transform.StringResult;

import com.derbysoft.ota.interfaces.protocol._2009a.OTAPingRQ;

public abstract class Jaxb2MarshallerHolder {

    private static Logger logger = LoggerFactory.getLogger(Jaxb2MarshallerHolder.class);

    private static Jaxb2Marshaller instance = new Jaxb2Marshaller();

    private static Exception failed;

    static {
        initialize();
    }

	private static void initialize() {
		instance.setContextPath(OTAPingRQ.class.getPackage().getName());
        try {
            instance.afterPropertiesSet();
        } catch (Exception e) {
            logger.error(e.toString(), e);
            failed = e;
        }
	}

    public static Jaxb2Marshaller get() {
        if (failed != null) {
            throw new RuntimeException("Failed to create jaxb2Marshaller", failed);
        }
        return instance;
    }
    
    public static JAXBContext getContext() {
    	return get().getJaxbContext();
    }
    
    public static String marshall(Object o) {
		Result result = new StringResult();
		get().marshal(o, result);
		return result.toString();
    }
    
}
